//
//  HMEmotionViewCell.swift
//  Weibo
//
//  Created by Apple on 2017/7/17.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit
//  自定义表情视图cell
class HMEmotionViewCell: UICollectionViewCell {
    
    //  记录20个表情按钮
    fileprivate lazy var emoticonButtonArray: [HMEmoticonButton] = [HMEmoticonButton]()
    
    //  表情模型数据
    var emoticonArray: [HMEmoticon]? {
        didSet {
            guard let currentEmoticonArray = emoticonArray else {
                return
            }
            
            //  隐藏所有的表情按钮
            for emotionButton in emoticonButtonArray {
                emotionButton.isHidden = true
            }
            
            //  遍历模型数组给表情按钮赋值
            for (i, emoticon) in currentEmoticonArray.enumerated() {
                //  获取表情按钮
                let button = emoticonButtonArray[i]
                //  绑定模型
                button.emoticon = emoticon
                
            }
        }
    }
    
    //  MARK:   --懒加载控件
    fileprivate lazy var messageLabel: UILabel = {
        let label = UILabel(fontSize: 20, textColor: UIColor.brown)
        return label
    }()
    
    
    var indexPath: IndexPath? {
        didSet {
            guard let currentIndexPath = indexPath else {
                return
            }
            messageLabel.text = "当前显示的是第\(currentIndexPath.section + 1)组第\(currentIndexPath.item + 1)页"
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件设置约束
    private func setupUI() {
        addChildButton()
        contentView.addSubview(messageLabel)
        messageLabel.snp.makeConstraints { (make) in
            make.center.equalTo(contentView)
        }
    }
    
    //  添加20个表情按钮
    private func addChildButton() {
        //  表情按钮的宽度
        let buttonWidth = width / 7
        //  表情按钮的高度
        let buttonHeight = height / 3
        for i in 0..<20 {
            //  列的索引
            let colIndex = i % 7
            //  行的索引
            let rowIndex = i / 7
            let button = HMEmoticonButton()
            //  添加点击事件
            button.addTarget(self, action: #selector(emoticonButtonAction(btn:)), for: .touchUpInside)
            button.x = CGFloat(colIndex) * buttonWidth
            button.y = CGFloat(rowIndex) * buttonHeight
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 33)
            contentView.addSubview(button)
            emoticonButtonArray.append(button)
        }
    }
    
    //  MARK:   --表情按钮点击事件处理
    @objc private func emoticonButtonAction(btn: HMEmoticonButton) {
        let emoticon = btn.emoticon!
        //  发送通知
        NotificationCenter.default.post(name: NSNotification.Name(ClickEmoticonButonNotificationName), object: emoticon)
    }
    
}
